<template>
	<view class="chat">
    <!-- 顶部标题 -->
    <view class="topTabbar">
      <!-- 返回图标 -->
      <u-icon class="icon" name="arrow-left" size="20px" color="#000" @click="goback()"></u-icon>
      <!-- 标题 -->
      <view class="text">果壳悦食Ai</view>
	  <u-tag text="专业版" shape="circle" mode="light"/>
	  <u-switch :disabled="isloading" v-model="user_mode"></u-switch>
		
	  <view >
	  	<u-modal :show="modal_show" :title="modal_title" :content='modal_content' :closeOnClickOverlay="true" @confirm="modal_confirm()"></u-modal>
	  </view>
    </view>
		<scroll-view  :style="{height: `${windowHeight-keyboardHeight+350}rpx`}"
		id="scrollview"
		scroll-y="true" 
		:scroll-top="scrollTop"
		class="scroll-view"
		>
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="item self" v-if="item.userContent != ''" >
						<!-- 文字内容 -->
						<view class="content right">
						{{item.userContent}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.image">
						</image>
					</view>
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-if="item.botContent != ''">
						<!-- 头像 -->     
						<image class="avatar" :src="item.image">
						</image>
						<!-- 文字内容 -->
						<view class="content left">
							{{item.botContent}}
						</view>
					</view>
				</view>
				<div v-if="isloading">
					<uni-load-more color="#007AFF" iconType="circle" :status="loading" />
				</div>
				
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${bottomHeight-20}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight+50}rpx`}">
        <view class="uni-textarea">
          <textarea :disabled="isloading" v-model="chatMsg"
            maxlength="300"
            confirm-type="send"
            @confirm="handleSend"
            placeholder="快来聊天吧~"
            :show-confirm-bar="false"
            :adjust-position="false"
            @linechange="sendHeight"
            @focus="focus" @blur="blur"
           auto-height></textarea>
        </view>
		<button :disabled="isloading" @click="handleSend" class="send-btn">发送</button>
	
		
			</view>
		</view>
	</view>
</template>
<script>
	export default{
		data() {
			return {
				userName:"",
				userGender:"",
				userAge:"",
				userWeight:"",
				userHeight:"",
				aiImg_path:"",
				user_mode:false,
				error:null,
				loading:'loading',
				isloading:false,
				tempmsg:"",
				//键盘高度
				modal_show:false,
				modal_title:'警告！',
				modal_content:'输入内容不能为空！',
				keyboardHeight:0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				userId:'',
				//发送的消息
				chatMsg:"",
				msgList:[
					{
					    botContent: "你好啊，我是果壳悦食AI机器人，请问我有什么可以帮助你的吗？",
					    userContent: "",
              image:"/static/aiAvatar.svg"
					},
					{
					    botContent: "",
					    userContent: "你好呀，非常高兴认识你",
              image:"/static/userAvatar.svg"
					},
				]	
			}
		},
		updated(){
			
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
			    return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight(){
				return this.bottomHeight
			}
		},
		onLoad(){
			this.loadUserInfo();
			
			uni.onKeyboardHeightChange(res => {
				this.keyboardHeight = 0;
			})
		},
		onShow() {
			this.loadUserInfo();
		},
		onUnload(){
			
			// uni.offKeyboardHeightChange()
		},
		methods: {
			async loadUserInfo() {
				await uni.request({
					url: `${this.$baseUrl}/user/getMessage`, // 反引号引用url
					method: 'POST',
					header: {
						'Authorization': 'Bearer ' + uni.getStorageSync('access_token') // 携带 Token，获取id
					},
				}).then(([err, res]) => {
					if (!err && res.data.data) {
						this.userName = res.data.data[0]["name"];
						this.userGender= res.data.data[0]["gender"];
						this.userAge = res.data.data[0]["age"];
						this.userWeight = res.data.data[0]["weight"];
						this.userHeight = res.data.data[0]["height"];
					} else {
						this.showPrompt("网络繁忙，请稍后重试");
					}
				});
			},
			goback() {
				uni.switchTab({
					url: "/pages/index/homepage"
				})
			},
			focus(){
				this.scrollToBottom()
			},
			blur(){
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px){
				let deviceHeight = uni.getSystemInfoSync().windowHeight
				let rpx = ( 750 / deviceHeight ) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight(){
				setTimeout(()=>{
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res =>{
						this.bottomHeight = this.rpxTopx(res[0].height)
						
					})
				},10)
			},
			// 滚动至聊天底部
			scrollToBottom(e){
				setTimeout(()=>{
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) =>{
						if(res[1].height > res[0].height){
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				},15)
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				if(!(this.chatMsg=="") && !/^\s+$/.test(this.chatMsg)){
					let obj = {
						botContent: "",
						userContent: this.chatMsg,
						image:"/static/userAvatar.svg"
					}
					this.msgList.push(obj);
					this.tempmsg=this.chatMsg;
					this.chatMsg = '';
					this.scrollToBottom()
					//调用ai大模型处理
					//等待加载处理
					this.isloading=true;
					this.error=null;
					
					
					uni.request({
						url:`${this.$baseUrl}/chat`,
						method:'POST',
						header:{
							'Contene-Type':'application/json'
						},
						data:{
							body:this.tempmsg,
							type:this.user_mode,
							gender:this.userGender,
							age:this.userAge,
							weight:this.userWeight,
							height:this.userHeight
						},
						success: (res) => {
							if(res.statusCode === 200){
								//得到返回数据
								console.log('成功获取到数据！');
								let obj = {
									botContent: res.data,
									userContent:"",
									image:"/static/aiAvatar.svg"
								}
								if(this.user_mode){
									obj.image="/static/aiAvatarPlus.svg"
								}
								this.msgList.push(obj);
								this.scrollToBottom()
							}else{
								this.error='请求大模型失败！';
							}
						},
						fail: (err) => {
							console.log('请求失败！')
							this.error=err.errMsg;
						},
						complete: () => {
							console.log('请求完成！')
							//结束加载状态
							this.isloading=false;
						}
					});
				//如果输入消息为空,将警示框展示。
				}else {
					this.modal_show=true;
					this.chatMsg="";
				}
			},
			modal_confirm(){
				this.modal_show=false;
			}
		}
	}
</script>
<style lang="scss" scoped>
	
	$chatContentbgc: #C2DCFF;
	$sendBtnbgc: #4F7DF5;
	
	view,button,text,input,textarea {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}
 
	/* 聊天消息 */
	.chat {
     .topTabbar {
          width: 100%;
          height: 90rpx;
          line-height: 90rpx;
          display: flex;
          margin-top: 80rpx;
          justify-content: space-between;
      
          .icon {
            margin-left: 20rpx;
          }
      
          .text {
            margin: auto;
            font-size: 18px;
            font-weight: 700;
			justify-content: center; /* 水平居中 */
			align-items: center; 
          }
      
          .button {
            width: 10%;
            margin: auto 20rpx auto 0rpx;
          }
        }
		.scroll-view {
			::-webkit-scrollbar {
					    display: none;
					    width: 0 !important;
					    height: 0 !important;
					    -webkit-appearance: none;
					    background: transparent;
					    color: transparent;
					  }
			
			// background-color: orange;
			background-color: #F6F6F6;
			
			.chat-body {
				display: flex;
				flex-direction: column;
				padding-top: 23rpx;
				// background-color:skyblue;
				
				.self {
					justify-content: flex-end;
				}
				.item {
					display: flex;
					padding: 23rpx 30rpx;
					// background-color: greenyellow;
 
					.right {
						background-color: $chatContentbgc;
					}
					.left {
						background-color: #FFFFFF;
					}
                    // 聊天消息的三角形
					.right::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						left: 100%;
						top: 10px;
						border: 12rpx solid transparent;
						border-left: 12rpx solid $chatContentbgc;
					}
 
					.left::after {
						position: absolute;
						display: inline-block;
						content: '';
						width: 0;
						height: 0;
						top: 10px;
						right: 100%;
						border: 12rpx solid transparent;
						border-right: 12rpx solid #FFFFFF;
					}
 
					.content {
						position: relative;
						max-width: 60%;
						
						border-radius: 8rpx;
						word-wrap: break-word;
						padding: 24rpx 24rpx;
						margin: 0 24rpx;
						border-radius: 5px;
						font-size: 32rpx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #333333;
						line-height: 42rpx;
					}
 
					.avatar {
						display: flex;
						justify-content: center;
						min-width: 78rpx;
						width: 78rpx;
						height: 78rpx;
						background: $sendBtnbgc;
						border-radius: 50rpx;
						overflow: hidden;
						
						image {
							align-self: center;
						}
 
					}
				}
			}
		}
 
		/* 底部聊天发送栏 */
		.chat-bottom {
			width: 100%;
			height: 100rpx;
			background: #F4F5F7;
			transition: all 0.1s ease;
			
			.send-msg {
				display: flex;
				flex-direction: row;
				align-items: flex-end;
				padding: 0rpx 0rpx;
				width: 100%;
				min-height: 177rpx;
				position: fixed;
				bottom: 0;
				background: #fff;
				transition: all 0.1s ease;
			}
 
			.uni-textarea {
				padding-bottom: 70rpx;  
				width:85%;
				textarea {
					width: 100%;
					min-height: 75rpx;
					max-height: 500rpx;
					background: #f1f1f1;
					border-radius: 40rpx;
					font-size: 32rpx;
					font-family: PingFang SC;
					color: #333333;
					line-height: 74rpx;
					padding: 5rpx 8rpx;
          text-indent: 30rpx;
				}
			}
            
			.send-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 76rpx;
				margin-left: 25rpx;
				width: 15%;
				height: 75rpx;
				background: #ed5a65;
				border-radius: 50rpx;
				font-size: 28rpx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				line-height: 28rpx;
			}
			

			
			
		}
	}
</style>